package com.dbflow5.query;

import com.dbflow5.SqlUtils;
import com.dbflow5.database.DatabaseWrapper;
import com.dbflow5.sql.Query;

import java.util.ArrayList;
import java.util.List;

/**
 * Description: The last piece of a TRIGGER statement, this class contains the BEGIN...END and the logic in between.
 */
public class CompletedTrigger<TModel> implements Query {

    private final TriggerMethod<TModel> triggerMethod;

    /**
     * The query to run between the BEGIN and END of this statement
     */
    private final List<Query> triggerLogicQuery = new ArrayList<>();

    public CompletedTrigger(TriggerMethod<TModel> triggerMethod, Query triggerLogicQuery){
        this.triggerMethod = triggerMethod;
        this.triggerLogicQuery.add(triggerLogicQuery);
    }

    @Override
    public String getQuery() {
        StringBuilder builder = new StringBuilder();
        for (int index=0;index<triggerLogicQuery.size();index++){
            String query = triggerLogicQuery.get(index).getQuery();
            builder.append(query);
            if(index != triggerLogicQuery.size() - 1){
                builder.append(";\n");
            }
        }
        return triggerMethod.getQuery() + "\nBEGIN\n"+builder.toString()+";\nEND";
    }

    /**
     * Appends the nextStatement to this query as another line to be executed by trigger.
     *
     * @param nextStatement nextStatement
     * @return this
     */
    public CompletedTrigger<TModel> and(Query nextStatement) {
        this.triggerLogicQuery.add(nextStatement);
        return this;
    }

    /**
     * Turns on this trigger
     *
     * @param databaseWrapper databaseWrapper execSQL
     */
    public void enable(DatabaseWrapper databaseWrapper) {
        databaseWrapper.execSQL(getQuery());
    }

    /**
     * Disables this trigger
     *
     * @param databaseWrapper databaseWrapper dropTrigger
     */
    public void disable(DatabaseWrapper databaseWrapper) {
        SqlUtils.dropTrigger(databaseWrapper, triggerMethod.trigger.name);
    }
}
